package com.sxjh.common;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.cglib.CglibUtil;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxjh.entity.PageEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

/**
 * @author zixin
 * @since 2021-05-05
 * 基础控制器
 */
public class BaseController {

  protected final Logger logger = LoggerFactory.getLogger(this.getClass());

  // 提取出参数中的页码和条数
  public IPage<Void> getIPage(PageEntity pageEntity) {
    IPage<Void> iPage = new Page<>();
    long size = pageEntity.getSize();
    long current = pageEntity.getCurrent();
    if (size <= 0) size = Constant.size;
    if (current <= 0) current = Constant.current;
    iPage.setSize(size);
    iPage.setCurrent(current);
    return iPage;
  }

  // 列表数据拷贝
  protected <T, E>List<T> copyList(List<E> list ,Supplier<T> target) {
    return CglibUtil.copyList(list, target);
  }

  // 分页数据拷贝
  protected <T, E>ZPage<T> copyPage(IPage<E> iPage, Supplier<T> target) {
    ZPage<T> zPage = new ZPage<>();
    zPage.setPages(iPage.getPages());
    zPage.setCurrent(iPage.getCurrent());
    zPage.setSize(iPage.getSize());
    zPage.setTotal(iPage.getTotal());
    if (iPage.getRecords() == null || iPage.getRecords().size() <= 0) {
      zPage.setRecords(new ArrayList<>());
    }
    List<T> records = CglibUtil.copyList(iPage.getRecords(), target);
    zPage.setRecords(records);
    return zPage;
  }

  protected <T, E>ZPage<T> copyPage(IPage<E> iPage, List<T> target) {
    ZPage<T> zPage = new ZPage<>();
    zPage.setPages(iPage.getPages());
    zPage.setCurrent(iPage.getCurrent());
    zPage.setSize(iPage.getSize());
    zPage.setTotal(iPage.getTotal());
    zPage.setRecords(target);
    return zPage;
  }

  public Integer getUserInfo(HttpServletRequest request) {
    String token = request.getHeader("Authorization");
    // 设置用户信息
    Integer id = null;
    if (StrUtil.isNotBlank(token) && token.length() > 8) {
      String token2 = token.substring(7);
      try {
        id = JWT.decode(token2).getClaim("sub").asInt();
      } catch (Exception e) {
        logger.error(e.getMessage(), e);
      }
    }
    return id;
  }

  // 返回对象方法
  protected <T>Result<T> err(String msg) {
    return Result.err(msg);
  }
  protected <T>Result<T> err() {
    return Result.err();
  }
  protected Result<Void> ok() {
    return Result.ok();
  }
  protected <T>Result<T> ok(T data) {
    return Result.ok(data);
  }
  protected <T>Result<T> cus(Integer code, String msg, T data) {
    return Result.cus(code, msg, data);
  }
  protected Result<Void> cus(Integer code, String msg) {
    return Result.cus(code, msg);
  }
}